//
//  PhotosListViewController.m
//  Paparazzi
//
//  Created by Miguel Sánchez Valdés on 27/04/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "PhotosListViewController.h"

@implementation PhotosListViewController

@synthesize person,sharedContext;



/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


-(id)initWithStyle :(UITableViewStyle)style{
	
	if (self = [super initWithStyle:style])
	{
		FlickrFetcher *flickrFetcher = [FlickrFetcher sharedInstance];
		sharedContext = [flickrFetcher managedObjectContext];	
	}
	return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

	[super viewDidLoad];
	
	// Set up the buttons.
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
	
	NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Photo" inManagedObjectContext:sharedContext];
	[request setEntity:entity];
	
	NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
	[request setSortDescriptors:sortDescriptors];
	[request setFetchBatchSize:(NSUInteger)20];
	[sortDescriptors release];
	//[sortDescriptor release];
	
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"owner=%@", person];
	[request setPredicate:predicate];
	
	fetcherResultsController = [[NSFetchedResultsController alloc]
								initWithFetchRequest:request
								managedObjectContext:sharedContext
								sectionNameKeyPath:nil
								//cacheName:@"tempPerson"];
								cacheName:nil];

	
	[request release];
	
	NSError *error;
	[fetcherResultsController performFetch:&error];
	
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	
	NSInteger size = [[fetcherResultsController sections] count];
	if (size == 0) {
		size = 1;
	}
    return size;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	NSArray *sections = [fetcherResultsController sections];
	NSInteger count = 0;
	
	if ([sections count]) {
		id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
		count = [sectionInfo numberOfObjects];
	}
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	// CELDA ESTILIZADA: TUTORIAL DE DEVELOPERS DE APPLE
	// http://developer.apple.com/iphone/library/documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7
	
	static NSString *CellIdentifier = @"ImageOnRightCell";
	
    UILabel *mainLabel, *secondLabel;
    UIImageView *photoView;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
		
        mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)] autorelease];
        mainLabel.tag = MAINLABEL_TAG;
        mainLabel.font = [UIFont systemFontOfSize:14.0];
        mainLabel.textAlignment = UITextAlignmentRight;
        mainLabel.textColor = [UIColor blackColor];
        mainLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
        [cell.contentView addSubview:mainLabel];
		
        secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 20.0, 220.0, 25.0)] autorelease];
        secondLabel.tag = SECONDLABEL_TAG;
        secondLabel.font = [UIFont systemFontOfSize:12.0];
        secondLabel.textAlignment = UITextAlignmentRight;
        secondLabel.textColor = [UIColor darkGrayColor];
        secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
        [cell.contentView addSubview:secondLabel];
		
        photoView = [[[UIImageView alloc] initWithFrame:CGRectMake(225.0, 0.0, 80.0, 45.0)] autorelease];
        photoView.tag = PHOTO_TAG;
        photoView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
        [cell.contentView addSubview:photoView];
    } else {
        mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
        secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
        photoView = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG];
    }
	
	Photo *photo = (Photo *)[fetcherResultsController objectAtIndexPath:indexPath];

    //NSDictionary *aDict = [self.list objectAtIndex:indexPath.row];
    mainLabel.text = [photo name];
    secondLabel.text = [photo path];
    //NSString *imagePath = [[NSBundle mainBundle] pathForResource:[photo path] ofType:@"jpg"];
    UIImage *theImage = [UIImage imageNamed:[photo path]];
    photoView.image = theImage;
	
    return cell;
	
	/// ESTILO BASICO SIN GRACIA
	/*
    static NSString *CellIdentifier = @"Cell";
	
    // Dequeue or create a new cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
	
    Photo *photo = (Photo *)[fetcherResultsController objectAtIndexPath:indexPath];
	
    cell.textLabel.text = [photo name];
	cell.imageView.image = [UIImage imageNamed:[photo path]];
	cell.imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
	cell.detailTextLabel.text = [photo path];

	
	return [cell autorelease];
	 
	*/
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	
	selPhotoView = [[PhotoDetailViewController alloc] init];
	Photo *photo = (Photo *)[fetcherResultsController objectAtIndexPath:indexPath];
	NSLog(@"%@",[photo name]);
	selPhotoView.selectedPhoto = [UIImage imageNamed:[photo path]];
	selPhotoView.selectedTitle = [NSString stringWithFormat:@"%@", [photo name]];
	
	[self.navigationController pushViewController:selPhotoView animated:YES];
	
}



/*
- (void)pushViewController:(NSString *)name{
	
	PhotoShowedViewController *photoShowedViewController = [[PhotoShowedViewController alloc] init];
	//photosListViewController.title = [NSString stringWithFormat:@"Fotos de %@", name];
	photoShowedViewController.label = name;
	
	[self.navigationController pushViewController:photoShowedViewController animated:YES];
	[photoShowedViewController release];
	
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	
	//[fetcherResultsController deleteCacheWithName:@"tempPerson"];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}


- (void)dealloc {
	[selPhotoView release];
	[sharedContext release];
	[fetcherResultsController release];
	[person release];  
    [super dealloc];
}


@end
